<template>
	<el-card>
		<div slot="header">
			<span>文章发表</span>
		</div>
		<el-form ref="form" :model="form" label-width="80px">
			<el-form-item label="标题">
				<el-input v-model="form.title"></el-input>
			</el-form-item>
			<el-form-item label="描述">
				<el-input type="textarea" v-model="form.description"></el-input>
			</el-form-item>
			<el-form-item label="分类">
				<el-col :span="6">
					<el-select v-model="form.cate_1st" placeholder="请选择">
						<el-option v-for="item in cate_1st_options" :label="item.cate_name" :key="item.cate_id"
							:value="item.cate_id">
						</el-option>
					</el-select>
				</el-col>
				<el-col :span="6">
					<el-select v-model="form.cate_2nd" placeholder="请选择">
						<el-option v-for="item in cate_2nd_options" :label="item.cate_name" :key="item.cate_id"
							:value="item.cate_id">
						</el-option>
					</el-select>
				</el-col>
			</el-form-item>
			<el-form-item label="主图">
				<Upload_Picture v-model="form.main_photo" :data="{ type: 'common' }"></Upload_Picture>
			</el-form-item>
			<el-form-item label="内容">
				<Edit_Tool v-model="form.content"></Edit_Tool>
			</el-form-item>
			<el-form-item>
				<el-button @click="handleInsert" type="primary">发布文章</el-button>
			</el-form-item>
		</el-form>
	</el-card>
</template>

<script>
import { Article, Category } from '@/api';
import Upload_Picture from '@/plugins/upload-picture.vue';
import Edit_Tool from '@/plugins/edit-tool.vue';

export default {
	components: {  Upload_Picture, Edit_Tool },
	data() {
		return {
			form: {
				cate_1st: '',
				cate_2nd: '',
				title: '',
				description: '',
				main_photo: '',
				content: '',
			},
			cate_1st_options: [],
			cate_2nd_options: [],
		}
	},
	async created() {
		// 加载一级分类
		this.cate_1st_options = await this.loadSubcate(0);
		this.form.cate_1st = this.cate_1st_options[0]?.cate_id;
	},
	watch: {
		async "form.cate_1st"(newValue, oldValue) {
			this.cate_2nd_options = await this.loadSubcate(newValue);
			this.form.cate_2nd = this.cate_2nd_options[0]?.cate_id;
		}
	},
	methods: {
		async loadSubcate(cate_id) {
			let { status, data } = await Category.sub({ cate_id });
			if (status) {
				return data;
			}
		},
		handleInsert() {
			this.$refs.form.validate(async (valid) => {
				if (valid) {
					let { status, msg, data } = await Article.release({ ...this.form });
					if (status) {
						// 信息提示
						this.$message.success(msg);
						this.$router.push('/article/list')
					} else {
						// 信息提示
						this.$message.error(msg);
					}
				}
			});
		},
	},
}
</script>

<style></style>
